<template>
  <div class="chat-container">
    <!-- 头部 -->
    <div class="title">
      <div class="title-left">
        <img src="../../assets/realLogoAi.png" alt="AI助手" class="ai-logo">
        <div class="title-text">
          <span class="titleName">劳动用工风控小助手 ｜ 劳小易</span>
          <span class="timeTitle">24小时竭诚为您服务</span>
        </div>
      </div>
      <el-icon class="close-icon" @click="$emit('close')">
        <Close />
      </el-icon>
    </div>

    <!-- 推荐问题区域 -->
    <div class="question">
      <div class="questionTitle">
        <div class="guess">猜你想问</div>
        <div class="change" @click="handleChangeQuestions">
          换一批
          <div class="changeIcon">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="17" viewBox="0 0 16 17" fill="none">
              <path d="M14 3.16675V8.50008" stroke="#007BFF" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/>
              <path d="M2 8.5V13.8333" stroke="#007BFF" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/>
              <path d="M14 8.5C14 5.1863 11.3137 2.5 8 2.5C6.30483 2.5 4.77387 3.20299 3.6827 4.33333M2 8.5C2 11.8137 4.6863 14.5 8 14.5C9.61853 14.5 11.0874 13.8591 12.1667 12.8173" stroke="#007BFF" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
          </div>
        </div>
      </div>

      <div class="titlecontent">
        <div
          class="questionItem"
          v-for="(item, index) in questionResult"
          :key="index"
          @click="fillInputWithQuestion(item)"
        >
          {{ index + 1 }}、{{ item }}
        </div>
      </div>
    </div>

    <!-- 聊天消息区域 -->
    <div class="chat-messages" ref="messagesContainer">
      <div v-for="(message, index) in messages" :key="index" class="message-wrapper">
        <div class="message-container">
          <!-- AI 消息 -->
          <div class="message-column ai-column">
            <div v-if="!message.isUser" class="message-content">
              <div class="avatar-wrapper">
                <div class="avatar ai-avatar">
                  <img src="@/assets/realLogoAi.png" alt="AI" class="avatar-img" />
                </div>
                <div class="name-label">劳小易</div>
              </div>
              <div class="message-bubble ai-message">{{ message.text }}</div>
            </div>
          </div>

          <!-- 用户消息 -->
          <div class="message-column user-column">
            <div v-if="message.isUser" class="message-content">
              <div class="message-bubble user-message">{{ message.text }}</div>
              <div class="avatar-wrapper">
                <div class="avatar user-avatar">
                  <img :src="userStore.avatar" alt="User" class="avatar-img" />
                </div>
                <div class="name-label">{{ userStore.user.userName }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 输入框区域 -->
    <div class="input-container">
      <div class="input-wrapper">
        <el-input
        type=textarea
          ref="inputRef"
           :rows="5"
          v-model="inputText"
          @keyup.enter="sendMessage"
          class="message-input"
          placeholder="请输入您想问的问题"
        />
        <button @click="sendMessage" class="send-button">
          <img src="@/assets/send.png" alt="发送" class="send-icon" />
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';
import useUserStore from "@/store/modules/user";
import questionData from '@/assets/question.json';
import { getRecords,apiCompletions} from '@/api/chat';
const inputRef = ref(null);
const messages = ref([
  { text: '你好！我是劳动用工风控小助手「劳小易」，点击上方问题或直接提问，我将为你解答', isUser: false },
]);
const questions = ref(questionData.labor_questions.map(item => item.question));
const usedIndexes = ref(new Set());
const questionResult = ref([]);
const inputText = ref('');
const messagesContainer = ref(null);
const userStore = useUserStore();
onMounted(() => {
  getChatRecords();
  // 首次加载随机问题
  getRandomQuestions(3);

  // 自动聚焦输入框（确保DOM渲染完成）
  nextTick(() => {
    inputRef.value?.focus();
  });
});
const getChatRecords = () => {
  getRecords().then(res => {
    console.log('获取聊天记录', res.data);
    if (res.data.newList && res.data.newList.length > 0) {
      messages.value = res.data.newList.map(item => ({
        text: item.content,
        isUser: item.type ? false : true,
      }));
      scrollToBottom(false); // 禁用滚动动画
    }
  });
};
// 滚动到底部
const scrollToBottom = (animated = true) => {
  nextTick(() => {
    messagesContainer.value?.scrollTo({
      top: messagesContainer.value.scrollHeight,
      behavior: animated ? 'smooth' : 'auto', // 根据参数决定是否启用动画
    });
  });
};

// 发送消息
const sendMessage = () => {
  const msg = inputText.value.trim();
  if (!msg) return;

  // 添加用户消息
  messages.value.push({ text: msg, isUser: true });
  inputText.value = '';
  scrollToBottom();

  // 调用 AI 回复逻辑
  simulateAIResponse(msg);
};

const simulateAIResponse = (question) => {
  console.log('question', question);

  // 添加“正在思考”占位消息
  const thinkingMessage = { text: '正在思考', isUser: false };
  messages.value.push(thinkingMessage);
  scrollToBottom();

  apiCompletions(question)
    .then((res) => {
      console.log('AI回复', res.msg);
      if (res.code === 200) {
        // 替换“正在思考”为实际回复
        const index = messages.value.indexOf(thinkingMessage);
        if (index !== -1) {
          messages.value[index].text = res.msg;
        }
        scrollToBottom();
      }
    })
    .catch((err) => {
      console.error('AI回复失败', err);

      // 替换“正在思考”为错误提示
      const index = messages.value.indexOf(thinkingMessage);
      if (index !== -1) {
        messages.value[index].text = '抱歉，AI服务暂时不可用，请稍后再试。';
      }
      scrollToBottom();
    });
};
// 获取随机问题（默认3条）
const getRandomQuestions = (count = 3) => {
  if (questions.value.length === 0) return;

  const allIndexes = Array.from({ length: questions.value.length }, (_, i) => i);
  const unusedIndexes = allIndexes.filter(i => !usedIndexes.value.has(i));
  const result = [];

  while (result.length < count && unusedIndexes.length > 0) {
    const idx = Math.floor(Math.random() * unusedIndexes.length);
    result.push(questions.value[unusedIndexes[idx]]);
    usedIndexes.value.add(unusedIndexes[idx]);
    unusedIndexes.splice(idx, 1);
  }

  // 重置索引（当所有问题用完时）
  if (unusedIndexes.length === 0) usedIndexes.value.clear();

  questionResult.value = result;
  console.log('当前推荐问题', result);
};

// 换一批问题
const handleChangeQuestions = () => {
  getRandomQuestions();
  scrollToBottom();
};

// 点击问题自动填充输入框
const fillInputWithQuestion = (text) => {
  inputText.value = text;
  inputRef.value?.focus();
  sendMessage()
  scrollToBottom();
};
</script>

<style lang="scss" scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f2f8ff;
  color: white;
  border-radius: 15px;
  opacity: 0.95;
}

.title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #F2F8FF;
  width: 100%;
  padding: 10px 15px;
  border-top-right-radius: 10px;
  border-top-left-radius: 10px;
  color: white;
  font-size: 16px;
  font-weight: 500;

  .title-left {
    display: flex;
    align-items: center;
    gap: 10px;

    .ai-logo {
      width: 32px;
      height: 32px;
      object-fit: contain;
    }

    .title-text {
      display: flex;
      flex-direction: column;

      .titleName {
        color: var(--Primary4-800, #383D48);
        font-family: "Source Han Sans CN";
        font-size: 14px;
        font-style: normal;
        font-weight: 700;
        line-height: normal;
      }

      .timeTitle {
        color: var(--Primary4-500, #6F7B90);
        font-family: "Source Han Sans CN";
        font-size: 12px;
        font-style: normal;
        font-weight: 400;
        line-height: normal;
      }
    }
  }

  .close-icon {
    cursor: pointer;
    font-size: 18px;
    transition: all 0.3s ease;
    color: #909399;

    &:hover {
      transform: rotate(90deg);
      color: #409EFF;
    }
  }
}

.chat-messages {
  flex: 1;
  padding: 10px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.message-wrapper {
  display: flex;
  width: 100%;
}

.message-container {
  display: flex;
  justify-content: space-between;
  margin: 4px 0;
  padding: 0 20px;
  width: 100%;
}

.message-column {
  width: 280px;
  display: flex;
  flex-direction: column;
}

.message-content {
  display: flex;
  align-items: flex-start;
  gap: 8px;
}

.ai-column .message-content {
  flex-direction: row;
}

.user-column .message-content {
  flex-direction: row;
  justify-content: flex-end;
}

.avatar-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  overflow: hidden;
}

.avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.name-label {
  font-size: 12px;
  color: #9CA3AF;
  white-space: nowrap;
}

.ai-avatar {
  background-color: #4B5563;
}

.user-avatar {
  background-color: #3B82F6;
}

.message-bubble {
  max-width: 100%;
  padding: 6px 12px;
  border-radius: 8px;
  font-size: 13px;
  line-height: 1.3;
  word-wrap: break-word;
  white-space: pre-wrap;
  text-align: left;
}

.user-message {
  background-color: #3b82f6;
  color: white;
  border-bottom-right-radius: 4px;
}

.ai-message {
  background-color: #374151;
  color: white;
  border-bottom-left-radius: 4px;
}

.input-container {
  padding: 16px;
  background-color: #f2f8ff;
  border-radius: 15px;
}

.input-wrapper {
  display: flex;
  align-items: center;
  gap: 16px;
  max-width: 800px;
  margin: 0 auto;
}

.message-input {
  flex: 1;
  padding: 8px 12px;
  border-radius: 8px;
  background-color: #fff;
  color: black;
  border: none;
  outline: none;
  font-size: 14px;
}

.message-input:focus {
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.5);
}

.send-button {
  padding: 8px;
  background-color: #3b82f6;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.send-button:hover {
  background-color: #2563eb;
}

.send-icon {
  width: 20px;
  height: 20px;
  object-fit: contain;
}

/* 自定义滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track {
  background: transparent;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.3);
}
.question{
  background-color: #fff;
    width: 80%;
    margin: 12px auto 12px auto;
    padding: 20px;
border-radius: 10px;
  .questionTitle{
    display: flex;
    align-items: center;
    justify-content: space-between;
    .guess{
      color: var(--Primary4-500, #6F7B90);
font-family: CKTKingkong;
font-size: 14px;
    }
    .change{
      display: flex;
      color: var(--Primary2-500, #007BFF);
font-family: "Source Han Sans CN";
font-size: 12px;
  .changeIcon{
    margin-left: 8px; 
    cursor: pointer
  }
  .changeIcon:active{
    transform: scale(0.9);
  }
    }
  }
  .titlecontent{
    margin: 10px auto;
    .questionItem{
cursor: pointer;
color: #000;
font-family: Inter;
font-size: 14px;
font-style: normal;
font-weight: 400;
line-height: normal;
}
  }

}
</style>